{#
 * ---------------------------------------------------------------------
 * GLPI - Gestionnaire Libre de Parc Informatique
 * Copyright (C) 2015-2018 Teclib' and contributors.
 *
 * http://glpi-project.org
 *
 * based on GLPI - Gestionnaire Libre de Parc Informatique
 * Copyright (C) 2003-2014 by the INDEPNET Development Team.
 *
 * ---------------------------------------------------------------------
 *
 * LICENSE
 *
 * This file is part of GLPI.
 *
 * GLPI is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * GLPI is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with GLPI. If not, see <http://www.gnu.org/licenses/>.
 * ---------------------------------------------------------------------
 #}
{% extends "glpi_page.twig" %}

{% block content_header %}
<header class="content-header">
    {% if head_dd is defined %}
        {% include "elements/select.twig" with {'element': head_dd, 'notag': true} %}
    {% endif %}
    {{ block('breadcrumb') }}
</header>
{% endblock %}

{% block content %}
   {% include "list_contents.twig" with {'main_header': true, form_header: true} %}
{% endblock %}

{% block javascripts %}
   {{ parent() }}
   {#TODO Load locale for moment.js#}
   <script type="text/javascript">
      $(function() {
         $('#default_items').on('click', function() {
            createModalWindow(
               CFG_GLPI.root_doc + '{{ path_for('display-preference', {'itemtype': (search_data is iterable ? search_data.itemtype) }) }}', {
                  'title': '{{ __('Select default items to show') }}',
                  {#'extraparams': '{{ {'target': base_path()}|json_encode(constant('JSON_FORCE_OBJECT')) }}',#}
                  'open': true
               }
            );
         });
                  {#$search_config_top
                  .= Ajax::createIframeModalWindow('search_config_top',
                                                   $CFG_GLPI["root_doc"].
                                                      "/front/displaypreference.form.php?itemtype=".
                                                      $data['itemtype'],
                                                   ['title'
                                                            => __('Select default items to show'),
                                                         'reloadonclose'
                                                            => true,
                                                         'display'
                                                            => false]);#}
         $('#btn_is_deleted').on('click', function(event) {
            event.preventDefault();
            toogle('is_deleted','','','');
            $('form#search_form').submit();
         });
         $('#btn_as_map').on('click', function(event) {
            event.preventDefault();
            toogle('as_map','','','');
            $('form#search_form').submit();
         });


         /* Botstap magic.. Does not worK.
            $('#search_criteria').boxWidget({
            collapseTrigger: '#toggle_search_criteria',
         });*/
         $('#toggle_search_criteria').on('click', function() {
            $('#search_criteria').toggle();
            $(this)
               .toggleClass('active')
         });

{% if search_data is iterable and search_data.search.as_map %}
          var map = initMap($('#map_container'), 'map', 'full');
          _loadMap(map, '{{ search_data.itemtype }}');
{% endif %}
      });

         var _loadMap = function(map_elt, itemtype) {
            L.AwesomeMarkers.Icon.prototype.options.prefix = 'fa';
            var _micon = 'circle';

            var stdMarker = L.AwesomeMarkers.icon({
               icon: _micon,
               markerColor: 'blue'
            });

            var aMarker = L.AwesomeMarkers.icon({
               icon: _micon,
               markerColor: 'cadetblue'
            });

            var bMarker = L.AwesomeMarkers.icon({
               icon: _micon,
               markerColor: 'purple'
            });

            var cMarker = L.AwesomeMarkers.icon({
               icon: _micon,
               markerColor: 'darkpurple'
            });

            var dMarker = L.AwesomeMarkers.icon({
               icon: _micon,
               markerColor: 'red'
            });

            var eMarker = L.AwesomeMarkers.icon({
               icon: _micon,
               markerColor: 'darkred'
            });

            //retrieve geojson data
            map_elt.spin(true);
            $.ajax({
               dataType: 'json',
               method: 'POST',
               url: '{{ path_for('map-results') }}',
               data: {
                  itemtype: itemtype,
                  params: {{ search_params|raw }}
               }
            }).done(function(data) {
               var _points = data.points;
               var _markers = L.markerClusterGroup({
                  iconCreateFunction: function(cluster) {
                     var childCount = cluster.getChildCount();

                     var markers = cluster.getAllChildMarkers();
                     var n = 0;
                     for (var i = 0; i < markers.length; i++) {
                        n += markers[i].count;
                     }

                     var c = ' marker-cluster-';
                     if (n < 10) {
                        c += 'small';
                     } else if (n < 100) {
                        c += 'medium';
                     } else {
                        c += 'large';
                     }

                     return new L.DivIcon({ html: '<div><span>' + n + '</span></div>', className: 'marker-cluster' + c, iconSize: new L.Point(40, 40) });
                  }
               });

               $.each(_points, function(index, point) {
                  {#var _title = '<strong>' + point.title + '</strong><br/><a href=\''+'$fulltarget'.replace(/CURLOCATION/, point.loc_id)+'\'>".sprintf(__('%1$s %2$s'), 'COUNT', $typename)."'.replace(/COUNT/, point.count)+'</a>';#}
                  var _title = '<strong>' + point.title + '</strong><br/><a href=\''+''.replace(/CURLOCATION/, point.loc_id)+'\'>' + ('COUNT ' + itemtype).replace(/COUNT/, point.count)+'</a>';
                  if (point.types) {
                     $.each(point.types, function(tindex, type) {
                       {#_title += '<br/>".sprintf(__('%1$s %2$s'), 'COUNT', 'TYPE')."'.replace(/COUNT/, type.count).replace(/TYPE/, itemtype);#}
                        _title += '<br/>COUNT TYPE'.replace(/COUNT/, type.count).replace(/TYPE/, itemtype);
                     });
                  }
                  var _icon = stdMarker;
                  if (point.count < 10) {
                     _icon = stdMarker;
                  } else if (point.count < 100) {
                     _icon = aMarker;
                  } else if (point.count < 1000) {
                     _icon = bMarker;
                  } else if (point.count < 5000) {
                     _icon = cMarker;
                  } else if (point.count < 10000) {
                     _icon = dMarker;
                  } else {
                     _icon = eMarker;
                  }
                  var _marker = L.marker([point.lat, point.lng], { icon: _icon, title: point.title });
                  _marker.count = point.count;
                  _marker.bindPopup(_title);
                  _markers.addLayer(_marker);
               });

               map_elt.addLayer(_markers);
               map_elt.fitBounds(
                  _markers.getBounds(), {
                     padding: [50, 50],
                     maxZoom: 12
                  }
               );
            }).fail(function (response) {
               var _data = response.responseJSON;
               var _message = '{{ __s('An error occured loading data :(') }}';
               if (_data.message) {
                  _message = _data.message;
               }
               var fail_info = L.control();
               fail_info.onAdd = function (map) {
                  this._div = L.DomUtil.create('div', 'fail_info');
                  this._div.innerHTML = _message + '<br/><span id=\'reload_data\'><i class=\'fa fa-sync\'></i> "{{ __s('Reload') }}</span>';
                  return this._div;
               };
               fail_info.addTo(map_elt);
               $('#reload_data').on('click', function() {
                  $('.fail_info').remove();
                  _loadMap(map_elt);
               });
            }).always(function() {
               //hide spinner
               map_elt.spin(false);
            });
         }

   </script>
{% endblock %}
